import *as types from '../actions/types'

const default_state = {
    homeworks: [],
    current_page: 1,
    end_of_page: false,
    loading: false,
    error: false,
    filter: null,
    per: 10
}

const homework = (state=default_state, action) => {
    switch (action.type) {
        case types.FETCHING_HOMEWORKS:
            return {
                ...state,
                loading: true           
            }
        case types.FETCH_HOMEWORK_SUCCESS:
            state.homeworks.push(...action.homeworks)
            return {
                ...state,
                homeworks: state.homeworks,
                loading: false,
                error: false,                
                current_page: state.current_page + 1
            }
        case types.HOMEWORK_END_OF_PAGE:
            return {
                ...state,
                end_of_page: true
            }
        case types.FETCH_HOMEWORK_FAIL:
            return {
                ...state,
                error: true
            }
        case types.REFRESH_HOMEWORKS:
            return {
                homeworks: [],
                current_page: 1,
                end_of_page: false,
                loading: false,
                error: false,
                per: 10
            }
        case types.UPDATE_HOMEWORK:
            let homework = (state.homeworks.filter((homework) => {
                return homework.id == action.id
            }))[0]
            if (homework != undefined) {
                Object.keys(action.param).forEach((key) => {
                    homework[key] = action.param[key]
                })
            }
            return {
                ...state,
                homeworks: state.homeworks
            }
        default: 
            return state    
    }
}

export default homework
